package entity;

/**
 * @author Kewen-Du
 * @date 2022/10/13
 */
public class Node<T> implements LinkedListNode<T>{
    //缓存节点值
    T value;

    //双向链表的引用
    private DoublyLinkedList<T> list;

    //下一节点
    private LinkedListNode<T> next;

    //上一节点
    private LinkedListNode<T> prev;

    public Node(T value, LinkedListNode<T> next, DoublyLinkedList<T> list) {
        this.value = value;
        this.next = next;
        this.setPrev(next.getPrev());
        this.prev.setNext(this);
        this.next.setPrev(this);
        this.list = list;
    }

    @Override
    public boolean hasElement() {
        return true;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public T getElement() {
        return value;
    }

    /**
     * Node1->Node2->Node3
     * 将Node2拆除
     * 将Node1.next指向Node3
     * 将Node3.pre指向Node1
     */
    @Override
    public void detach() {
        this.prev.setNext(this.getNext());
        this.next.setPrev(this.getPrev());
    }

    @Override
    public DoublyLinkedList<T> getListReference() {
        return this.list;
    }

    @Override
    public LinkedListNode<T> setPrev(LinkedListNode<T> prev) {
        this.prev = prev;
        return this;
    }

    @Override
    public LinkedListNode<T> setNext(LinkedListNode<T> next) {
        this.next = next;
        return this;
    }

    @Override
    public LinkedListNode<T> getPrev() {
        return this.prev;
    }

    @Override
    public LinkedListNode<T> getNext() {
        return this.next;
    }

    @Override
    public LinkedListNode<T> search(T value) {
        return this.getElement() == value ? this : this.getNext().search(value);
    }
}
